package com.bird.common.utils.covert;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.util.StdConverter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 系统用户转换
 *
 * @author: 李涛
 * @version: 2020年02月14日 17:46
 */
@Slf4j
public class GroupIdCovert extends StdConverter<Long, GroupIdCovert.GroupBean> {

	/**
	 * 字典翻译的bean引用
	 */
	public static final Object SPRING_BEAN = SpringUtil.getBean("tsGroupServiceImpl");

	/**
	 * 已存在的用户
	 */
	public static Map<Long, GroupBean> existUser = new ConcurrentHashMap();

	/**
	 * 错误查找的用户，30分钟失效
	 */
	private static TimedCache<Long, String> errorUser = CacheUtil.newTimedCache(TimeUnit.MINUTES.toMillis(30));

	@Override
	public GroupBean convert(Long id) {
		if (id == null || id < 0) {
			return null;
		}
		if (errorUser.containsKey(id)) {
			log.error("Cache-Group查找失败:{}!", id);
			return null;
		}
		GroupBean theBean = existUser.get(id);
		if (theBean == null) {
			theBean = new GroupBean();
			theBean.setId(id);
			String name = ReflectUtil.invoke(SPRING_BEAN, "selectNameById", id);
			if (name != null) {
				theBean.setName(name);
				existUser.put(id, theBean);
			} else {
				errorUser.put(id, id.toString());
				log.error("Group查找失败:{}!", id);
			}

		}
		return theBean;
	}

	/**
	 * 系统用户
	 */
	@Data
	public static class GroupBean {

		private Long id;

		private String name;

	}
}
